import { game, ui, _status, ai, lib, get } from "../../../noname.js";
import { swTool } from "../main/swTool.js";

export const doudizhu = {
	chooseMode() {
/*		swTool.onlineSelectNum = swTool.getSelect();*/
		const mode = _status.mode.slice(0, 1).toUpperCase() + _status.mode.slice(1);
		if (typeof game['chooseCharacter' + mode + 'OL'] === 'function') {
			game['chooseCharacter' + mode + 'OL']()
			return;
		}
		const next = game.createEvent('chooseCharacter');
		next.setContent(function () {
			"step 0"
			ui.arena.classList.add('choose-character');
			var i;
			var identityList = ['zhu', 'fan', 'fan'];
			identityList.randomSort();
			for (i = 0; i < game.players.length; i++) {
				game.players[i].identity = identityList[i];
				game.players[i].showIdentity();
				game.players[i].identityShown = true;
				if (identityList[i] == 'zhu') game.zhu = game.players[i];
			}

			var list;
			var list4 = [];
			event.list = [];

			var libCharacter = {};
			for (var i = 0; i < lib.configOL.characterPack.length; i++) {
				var pack = lib.characterPack[lib.configOL.characterPack[i]];
				for (var j in pack) {
					if (j == 'zuoci') continue;
					if (lib.character[j]) libCharacter[j] = pack[j];
				}
			}
			for (i in lib.characterReplace) {
				var ix = lib.characterReplace[i];
				for (var j = 0; j < ix.length; j++) {
					if (!libCharacter[ix[j]] || lib.filter.characterDisabled(ix[j], libCharacter)) ix.splice(j--, 1);
				}
				if (ix.length) {
					event.list.push(i);
					list4.addArray(ix);
				}
			}
			game.broadcast(function (list) {
				for (var i in lib.characterReplace) {
					var ix = lib.characterReplace[i];
					for (var j = 0; j < ix.length; j++) {
						if (!list.contains(ix[j])) ix.splice(j--, 1);
					}
				}
			}, list4);
			for (i in libCharacter) {
				if (list4.contains(i) || lib.filter.characterDisabled(i, libCharacter)) continue;
				event.list.push(i);
				list4.push(i)
			}
			_status.characterlist = list4;
			"step 1"
			var list = [];
			var selectButton = (lib.configOL.double_character ? 2 : 1);

			var num, num2 = 0;
			num = Math.floor(event.list.length / game.players.length);
			num2 = event.list.length - num * game.players.length;
			if (num > 5) {
				num = 5;
			}
			if (num2 > 2) {
				num2 = 2;
			}
			let selectNum = swTool.getSelect();
			for (var i = 0; i < game.players.length; i++) {
				var num3 = 0;
				if (game.players[i] == game.zhu) num3 = 3;
				var str = '欧尼酱~选择角色吧！';
				let snum = selectNum + num3;
				list.push([game.players[i], [str, [event.list.randomRemove(snum), 'characterx']], selectButton, true]);
			}
			game.me.chooseButtonOL(list, function (player, result) {
				if (game.online || player == game.me) player.init(result.links[0], result.links[1]);//选择角色完成
			});
			"step 2"
			for (var i in result) {
				if (result[i] && result[i].links) {
					for (var j = 0; j < result[i].links.length; j++) {
						event.list.remove(get.sourceCharacter(result[i].links[j]));
					}
				}
			}
			for (var i in result) {
				if (result[i] == 'ai') {
					var listc = event.list.randomRemove(lib.configOL.double_character ? 2 : 1);
					for (var i = 0; i < listc.length; i++) {
						var listx = lib.characterReplace[listc[i]];
						if (listx && listx.length) listc[i] = listx.randomGet();
					}
					result[i] = listc;
				}
				else {
					result[i] = result[i].links
				}
				if (!lib.playerOL[i].name) {
					lib.playerOL[i].init(result[i][0], result[i][1]);
				}
			}

			game.zhu.maxHp++;
			game.zhu.hp++;
			game.zhu.update();

			game.broadcast(function (result, zhu) {
				for (var i in result) {
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result[i][0], result[i][1]);
					}
				}
				game.zhu = zhu;
				zhu.maxHp++;
				zhu.hp++;
				zhu.update();

				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			}, result, game.zhu);
			for (var i = 0; i < game.players.length; i++) {
				_status.characterlist.remove(game.players[i].name1);
				_status.characterlist.remove(game.players[i].name2);
			}
			setTimeout(function () {
				ui.arena.classList.remove('choose-character');
			}, 500);
		});

	},
	modeConfig() {
		//TODD:额外选将时间的适配
		game.chooseCharacterKaiheiOL = function () {
			var next = game.createEvent('chooseCharacter');
			next.setContent(function () {
				"step 0"
				ui.arena.classList.add('choose-character');
				var i;
				var identityList = ['fan', 'fan', 'fan'];
				var aiList = game.filterPlayer(function (current) {
					return current != game.me && !current.isOnline();
				});
				if (aiList.length == 1) {
					identityList[game.players.indexOf(aiList[0])] = 'zhu';
				}
				else {
					identityList[0] = 'zhu';
					identityList.randomSort();
				}
				for (i = 0; i < game.players.length; i++) {
					game.players[i].identity = identityList[i];
					game.players[i].showIdentity();
					game.players[i].identityShown = true;
					if (identityList[i] == 'zhu') game.zhu = game.players[i];
				}
				event.list = [];
				var list4 = [];

				var libCharacter = {};
				for (var i = 0; i < lib.configOL.characterPack.length; i++) {
					var pack = lib.characterPack[lib.configOL.characterPack[i]];
					for (var j in pack) {
						// if(j=='zuoci') continue;
						if (lib.character[j]) libCharacter[j] = pack[j];
					}
				}
				for (i in lib.characterReplace) {
					var ix = lib.characterReplace[i];
					for (var j = 0; j < ix.length; j++) {
						if (!libCharacter[ix[j]] || lib.filter.characterDisabled(ix[j], libCharacter)) ix.splice(j--, 1);
					}
					if (ix.length) {
						event.list.push(ix.randomGet());
						list4.addArray(ix);
					}
				}
				for (i in libCharacter) {
					if (list4.includes(i) || lib.filter.characterDisabled(i, libCharacter)) continue;
					event.list.push(i);
				}
				_status.characterlist = event.list.slice(0);

				var map = {};
				const num = swTool.getSelect(event.list);
				for (var player of game.players) {
					player._characterChoice = event.list.randomRemove(num + (player.identity == 'zhu' ? 5 : 3));
					if (player.identity == 'fan') player._friend = (player.next.identity == 'fan' ? player.next : player.previous);
					map[player.playerid] = player._characterChoice;
				}
				game.broadcastAll(function (map) {
					for (var i in map) {
						lib.playerOL[i]._characterChoice = map[i];
					}
				}, map);
				"step 1"
				var list = [];
				for (var i = 0; i < game.players.length; i++) {
					var dialog = ['请选择武将', [game.players[i]._characterChoice, 'character']];
					if (game.players[i]._friend) {
						dialog.push('队友的武将');
						dialog.push([game.players[i]._friend._characterChoice, 'character']);
					}
					list.push([game.players[i], dialog, true, function () { return Math.random() }, function (button) {
						return _status.event.player._characterChoice.includes(button.link);
					}]);
				}
				game.me.chooseButtonOL(list, function (player, result) {
					if (game.online || player == game.me) player.init(result.links[0]);
				});
				"step 2"
				for (var i in lib.playerOL) {
					if (!result[i] || result[i] == 'ai' || !result[i].links || !result[i].links.length) {
						result[i] = lib.playerOL[i]._characterChoice.randomGet();
					}
					else {
						result[i] = result[i].links[0];
					}
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result[i]);
					}
				}

				game.zhu.maxHp++;
				game.zhu.hp++;
				game.zhu.update();

				game.broadcast(function (result, zhu) {
					for (var i in result) {
						if (!lib.playerOL[i].name) {
							lib.playerOL[i].init(result[i]);
						}
					}
					game.zhu = zhu;
					zhu.maxHp++;
					zhu.hp++;
					zhu.update();

					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				}, result, game.zhu);

				for (var i = 0; i < game.players.length; i++) {
					_status.characterlist.remove(game.players[i].name1);
					_status.characterlist.remove(game.players[i].name2);
				}
				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			});
		}
		game.chooseCharacterHuanleOL = function () {
			var next = game.createEvent('chooseCharacter');
			next.setContent(function () {
				"step 0"
				ui.arena.classList.add('choose-character');
				var i;
				event.list = [];
				event.list2 = [];
				var list4 = [];
				event.controls = ['不叫', '叫地主'];
				if (!event.map) event.map = {};
				var libCharacter = {};
				for (var i = 0; i < lib.configOL.characterPack.length; i++) {
					var pack = lib.characterPack[lib.configOL.characterPack[i]];
					for (var j in pack) {
						// if(j=='zuoci') continue;
						if (lib.character[j]) libCharacter[j] = pack[j];
					}
				}
				for (i in lib.characterReplace) {
					var ix = lib.characterReplace[i];
					for (var j = 0; j < ix.length; j++) {
						if (!libCharacter[ix[j]] || lib.filter.characterDisabled(ix[j], libCharacter)) ix.splice(j--, 1);
					}
					if (ix.length) {
						var name = ix.randomGet();
						event.list.push(name);
						if (game.recommendDizhu.includes(name)) event.list2.push(name);
						list4.addArray(ix);
					}
				}
				for (i in libCharacter) {
					if (list4.includes(i) || lib.filter.characterDisabled(i, libCharacter)) continue;
					event.list.push(i);
					if (game.recommendDizhu.includes(i)) event.list2.push(i);
				}
				const num = swTool.getSelect(event.list)
				for (var player of game.players) {
					var id = player.playerid;
					if (!event.map[id]) event.map[id] = [];
					event.map[id].addArray(event.list2.randomRemove(1));
					event.list.removeArray(event.map[id]);
					event.map[id].addArray(event.list.randomRemove(num - event.map[id].length));
					event.list2.removeArray(event.map[id]);
				}
				_status.characterlist = event.list.slice(0);
				event.videoId = lib.status.videoId++;
				game.broadcastAll(function (map, id) {
					ui.create.dialog('你的选将框', [map[game.me.playerid], 'character']).videoId = id;
				}, event.map, event.videoId);
				event.start = game.players.randomGet();
				event.current = event.start;
				if (event.current != game.me || !event.current.isOnline()) game.delay(3);
				"step 1"
				event.current.chooseControl(event.controls).set('ai', function () {
					return Math.random() > 0.5 ? '不叫' : '叫地主';
				});
				"step 2"
				event.current.chat(result.control);
				if (result.control == '叫地主' || event.current == event.start.next) {
					game.zhu = result.control == '叫地主' ? event.current : event.current.next;
					for (var player of game.players) {
						player.identity = player == game.zhu ? 'zhu' : 'fan';
						player.showIdentity();
						player.identityShown = true;
					}
					game.broadcastAll('closeDialog', event.videoId)
					event.map[game.zhu.playerid].addArray(event.list.randomRemove(3));
				}
				else {
					event.current = event.current.next;
					event.goto(1);
				}
				"step 3"
				var list = [];
				var str = '选择角色';
				for (var i = 0; i < game.players.length; i++) {
					list.push([game.players[i], [str, [event.map[game.players[i].playerid], 'character']], true]);
				}
				game.me.chooseButtonOL(list, function (player, result) {
					if (game.online || player == game.me) player.init(result.links[0], result.links[1]);
				});
				"step 4"
				for (var i in result) {
					if (result[i] && result[i].links) {
						for (var j = 0; j < result[i].links.length; j++) {
							event.list2.remove(result[i].links[j]);
						}
					}
				}
				for (var i in result) {
					if (result[i] == 'ai') {
						result[i] = event.list2.randomRemove(lib.configOL.double_character ? 2 : 1);
					}
					else {
						result[i] = result[i].links
					}
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result[i][0], result[i][1]);
					}
				}

				game.zhu.maxHp++;
				game.zhu.hp++;
				game.zhu.update();

				game.broadcast(function (result, zhu) {
					for (var i in result) {
						if (!lib.playerOL[i].name) {
							lib.playerOL[i].init(result[i][0], result[i][1]);
						}
					}
					game.zhu = zhu;
					zhu.maxHp++;
					zhu.hp++;
					zhu.update();

					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				}, result, game.zhu);
				for (var i = 0; i < game.players.length; i++) {
					_status.characterlist.remove(game.players[i].name1);
					_status.characterlist.remove(game.players[i].name2);
				}
				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			});
		}
		game.chooseCharacterBinglinOL = function () {
			var next = game.createEvent('chooseCharacter');
			next.setContent(function () {
				"step 0"
				ui.arena.classList.add('choose-character');
				var i;
				var libCharacter = {};
				for (var i = 0; i < lib.configOL.characterPack.length; i++) {
					var pack = lib.characterPack[lib.configOL.characterPack[i]];
					for (var j in pack) {
						// if(j=='zuoci') continue;
						if (lib.character[j]) libCharacter[j] = pack[j];
					}
				}
				event.list = [];
				event.map = {};
				for (i in libCharacter) {
					if (lib.filter.characterDisabled(i, libCharacter)) continue;
					event.list.push(i);
				}
				event.list.randomSort();
				_status.characterlist = event.list.slice(0);
				event.controls = ['不叫地主', '一倍', '两倍', '三倍'];
				const num = swTool.getSelect(event.list)
				for (var player of game.players) {
					var id = player.playerid;
					event.map[id] = event.list.randomRemove(num);
				}
				event.start = game.players.randomGet();
				event.current = event.start;

				event.videoId = lib.status.videoId++;
				game.zhuSkill = 'zhuSkill_' + ['xiangyang', 'jiangling', 'fancheng'].randomGet();
				game.broadcastAll(function (map, id, skill) {
					ui.create.dialog('本局城池：' + get.translation(skill), [map[game.me.playerid], 'character']).videoId = id;
				}, event.map, event.videoId, game.zhuSkill);
				game.delay(6);
				"step 1"
				game.broadcastAll(function (id, current) {
					var dialog = get.idDialog(id);
					if (dialog) {
						if (game.me == current) dialog.content.firstChild.innerHTML = '是否叫地主？';
						else dialog.content.firstChild.innerHTML = '请等待其他玩家叫地主';
					}
				}, event.videoId, event.current);
				if (event.current != game.me && !event.current.isOnline()) game.delay(2);
				event.current.chooseControl(event.controls).set('ai', function () {
					return _status.event.getParent().controls.randomGet();
				});
				"step 2"
				debugger
				event.current._control = result.control;
				event.current.chat(result.control);
				if (result.control == '三倍') {
					game.bonusNum = 3;
					game.zhu = event.current;
					return;
				}
				else if (result.control != '不叫地主') {
					event.controls.splice(1, event.controls.indexOf(result.control));
					event.tempDizhu = event.current;
					if (result.control == '二倍') game.bonusNum = 2;
				}
				event.current = event.current.next;
				if (event.current == event.start) {
					game.zhu = event.tempDizhu || event.start;
				}
				else event.goto(1);
				if (event.current == event.start.previous && !event.tempDizhu) event.controls.remove('不叫地主');
				"step 3"
				for (var player of game.players) {
					player.identity = player == game.zhu ? 'zhu' : 'fan';
					player.showIdentity();
					player.identityShown = true;
					player._characterChoice = event.map[player.playerid];
				}
				event.map[game.zhu.playerid].addArray(event.list.randomRemove(3));
				game.broadcastAll(function (id, map) {
					var dialog = get.idDialog(id);
					if (dialog) dialog.close();
					game.me._characterChoice = map[game.me.playerid];
				}, event.videoId, event.map);
				var list = [];
				for (var i = 0; i < game.players.length; i++) {
					var dialog = ['请选择武将', [event.map[game.players[i].playerid], 'character']];
					if (game.players[i].identity == 'fan') {
						var friend = game.findPlayer(function (current) {
							return current != game.players[i] && current.identity == 'fan';
						});
						dialog.push('<div class="text center">队友的选将框</div>');
						dialog.push([event.map[friend.playerid], 'character']);
					}
					list.push([game.players[i], dialog, true, function () { return Math.random() }, function (button) {
						return _status.event.player._characterChoice.includes(button.link);
					}]);
				}
				game.me.chooseButtonOL(list, function (player, result) {
					if (game.online || player == game.me) player.init(result.links[0]);
				});
				"step 4"
				for (var i in lib.playerOL) {
					if (!result[i] || result[i] == 'ai' || !result[i].links || !result[i].links.length) {
						result[i] = event.map[i].randomGet();
					}
					else {
						result[i] = result[i].links[0];
					}
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result[i]);
					}
				}

				game.zhu.maxHp++;
				game.zhu.hp++;
				game.zhu.update();

				game.broadcast(function (result, zhu) {
					for (var i in result) {
						if (!lib.playerOL[i].name) {
							lib.playerOL[i].init(result[i]);
						}
					}
					game.zhu = zhu;
					zhu.maxHp++;
					zhu.hp++;
					zhu.update();

					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				}, result, game.zhu);
				for (var player of game.players) {
					if (player == game.zhu) {
						player.addSkill(game.zhuSkill);
					}
					else player.addSkill(['binglin_shaxue', 'binglin_neihong']);
				}
				for (var i = 0; i < game.players.length; i++) {
					_status.characterlist.remove(game.players[i].name1);
					_status.characterlist.remove(game.players[i].name2);
				}
				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			});
		}
		game.chooseCharacterZhidouOL = function () {
			var next = game.createEvent('chooseCharacter');
			next.setContent(function () {
				"step 0"
				ui.arena.classList.add('choose-character');
				var i;
				var libCharacter = {};
				for (var i = 0; i < lib.configOL.characterPack.length; i++) {
					var pack = lib.characterPack[lib.configOL.characterPack[i]];
					for (var j in pack) {
						// if(j=='zuoci') continue;
						if (lib.character[j]) libCharacter[j] = pack[j];
					}
				}
				var groups = [];
				event.list = [];
				event.map = {};
				var chara = (get.config('character_online') || lib.characterOnline);
				for (i in chara) {
					var list = chara[i];
					for (var j = 0; j < list.length; j++) {
						if (!lib.character[list[j]] || lib.connectBanned.includes(list[j]) || (i == 'key' && lib.filter.characterDisabled(list[j], libCharacter))) list.splice(j--, 1);
					}
					if (list.length >= 3) {
						groups.push(i);
						event.list.addArray(list);
					}
				}
				event.list.randomSort();
				_status.characterlist = event.list.slice(0);
				event.controls = ['不叫地主', '一倍', '两倍', '三倍'];
				const num = swTool.getSelect(event.list)
				for (var player of game.players) {
					var id = player.playerid;
					player._group = groups.randomRemove(Math.floor(num / 2))[0];
					event.map[id] = chara[player._group].randomGets(Math.floor(num / 2));
					player.storage.doudizhu_cardPile = get.cards(20).sort(function (a, b) {
						if (a.name != b.name) return lib.sort.card(a.name, b.name);
						else if (a.suit != b.suit) return lib.suit.indexOf(a) - lib.suit.indexOf(b);
						else return a.number - b.number;
					});
					player.markSkill('doudizhu_cardPile');
				}
				event.start = game.players.randomGet();
				event.current = event.start;

				event.videoId = lib.status.videoId++;
				game.broadcastAll(function (map, id) {
					ui.create.dialog('你的选将框和底牌', [map[game.me.playerid], 'character'], game.me.storage.doudizhu_cardPile).videoId = id;
				}, event.map, event.videoId);
				game.delay(4);
				"step 1"
				game.broadcastAll(function (id, current) {
					var dialog = get.idDialog(id);
					if (dialog) {
						if (game.me == current) dialog.content.firstChild.innerHTML = '是否叫地主？';
						else dialog.content.firstChild.innerHTML = '请等待其他玩家叫地主';
					}
				}, event.videoId, event.current);
				if (event.current != game.me && !event.current.isOnline()) game.delay(2);
				event.current.chooseControl(event.controls).set('ai', function () {
					return _status.event.getParent().controls.randomGet();
				});
				"step 2"
				event.current._control = result.control;
				event.current.chat(result.control);
				if (result.control == '三倍') {
					game.bonusNum = 3;
					game.zhu = event.current;
					return;
				}
				else if (result.control != '不叫地主') {
					event.controls.splice(1, event.controls.indexOf(result.control));
					event.tempDizhu = event.current;
					if (result.control == '二倍') game.bonusNum = 2;
				}
				event.current = event.current.next;
				if (event.current == event.start && (event.start == event.tempDizhu || event.start._control == '不叫地主')) {
					game.zhu = event.tempDizhu || event.start.previous;
				}
				else if (event.current == event.start.next && event.current._control) {
					game.zhu = event.tempDizhu;
				}
				else event.goto(1);
				if (event.current == event.start.previous && !event.tempDizhu) event.controls.remove('不叫地主');
				"step 3"
				for (var player of game.players) {
					player.identity = player == game.zhu ? 'zhu' : 'fan';
					player.showIdentity();
					player.identityShown = true;
				}
				game.broadcastAll('closeDialog', event.videoId);
				var list = [];
				for (var i = 0; i < game.players.length; i++) {
					list.push([game.players[i], ['选择' + (game.players[i] == game.zhu ? '两' : '一') + '张武将牌', [event.map[game.players[i].playerid], 'character']], true, game.players[i] == game.zhu ? 2 : 1]);
				}
				game.me.chooseButtonOL(list, function (player, result) {
					if (game.online || player == game.me) player.init(result.links[0], result.links[1]);
				});
				"step 4"
				for (var i in result) {
					if (result[i] == 'ai') {
						result[i] = event.map[i].randomRemove(lib.playerOL[i] == game.zhu ? 2 : 1);
					}
					else {
						result[i] = result[i].links;
					}
					if (!lib.playerOL[i].name) {
						lib.playerOL[i].init(result[i][0], result[i][1]);
					}
				}

				game.zhu.hp = 4;
				game.zhu.maxHp = 4;
				game.zhu.update();

				game.broadcast(function (result, zhu) {
					for (var i in result) {
						if (!lib.playerOL[i].name) {
							lib.playerOL[i].init(result[i][0], result[i][1]);
						}
					}
					game.zhu = zhu;
					game.zhu.hp = 4;
					game.zhu.maxHp = 4;
					game.zhu.update();

					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				}, result, game.zhu);
				for (var i = 0; i < game.players.length; i++) {
					_status.characterlist.remove(game.players[i].name1);
					_status.characterlist.remove(game.players[i].name2);
				}
				setTimeout(function () {
					ui.arena.classList.remove('choose-character');
				}, 500);
			});
		}
		game.chooseCharacterFreeChoiceSkillOL = function () {
			//初始化部分1
			game.broadcast((vcardx,a,b) => {
				ui.create.buttonPresets.vcardx = vcardx
				lib.element.player.chooseItem = a
				lib.element.content.chooseItem = b
			}, ui.create.buttonPresets.vcardx, lib.element.player.chooseItem, lib.element.content.chooseItem)
			//这个东西挺重要的，需要它来制作选择的卡牌

			const characterList = Object.keys(swTool.initList());
			_status.characterlist = characterList.slice()

			//初始化一下武将

			_status.style = { innerHTML: swTool.playerInnerHTML }
			game.broadcastAll((list, innerHTML) => {
				const style = document.createElement('style')
				style.innerHTML = innerHTML
				document.head.appendChild(style)
				game.players.forEach((p, i) => {
					p.node.rightskillList = ui.create.div('.playerskillList', p)
					if (!p.nickname) {//||(p.ws&&!p.isOnline2())
						lib.character[list[i]][3] = []
						lib.character[list[i]][2] = 4
						p.init(list[i])
					}
				})
				game.me.update()
			}, characterList.randomGets(10), _status.style.innerHTML)
			//发送一个样式，就是技能的显示，这里看一下就好了

			const initPlayers = game.players.map(p => {
				if (p.ws || p === game.me) {
					let avatar
					let nickname
					if (p === game.me) {
						avatar = lib.config.connect_avatar
						nickname = lib.config.connect_nickname
					} else {
						avatar = p.ws.avatar
						nickname = p.nickname
					}
					game.addVideo('initAvatar', null, { avatar, nickname, playerid: p.playerid })
					return [p.playerid, avatar, nickname]
				}
			}).filter(Boolean)
			//筛选掉人机

			game.broadcastAll((players) => {
				players = players.map(p => [lib.playerOL[p[0]], p[1], p[2]])
				ui.arena.classList.add('choose-character');
				players.forEach(([player, avatar, name]) => {
					name = name.replace('※', '')
					const id = name + player.playerid
					let { 0: sex, 1: group, 2: hp, 3: skills, 4: fromTrash, 5: extraModeData } = lib.character[avatar]
					if (!fromTrash) fromTrash = [`character:${avatar}`]
					else fromTrash.push(`character:${avatar}`)
					lib.character[id] = new lib.element.Character([sex, group, 4, [], fromTrash, extraModeData])
					lib.translate[id] = name
					player.init(id)
					player.update()
				})
			}, initPlayers)
			//然后初始化一下玩家们
			const next = game.createEvent('chooseCharacter')
			next.setContent(async function (event) {
				let skillList = [];
				let map = {};
				const zhuMoreListNum = parseInt(lib.configOL.doudizhu_zhuMoreListNum)
				const chooseSkillNum = parseInt(lib.configOL.doudizhu_freeChoiceSkillNum)
				const zhuMoreSkillNum = parseInt(lib.configOL.doudizhu_zhuMoreSkillNum)
				function init() {
					skillList = []
					map = {}
					lib.skillReplace = {}
					lib.playerSkillOL = {}
					_status.playerCharacters = {}
					_status.skillMap = {}
					_status.zhuSkills = {}
					lib.playerCharacterOL = {}

					swTool.getSkillMapOfCharacter(_status.characterlist, (skill, name) => {
						const translate = lib.translate[skill]
						if (!lib.skillReplace[translate]) {
							lib.skillReplace[translate] = []
							skillList.push({ skill, name })
						}
						const group = lib.character[name].group
						const theSkill = lib.skill[skill]
						if (theSkill && theSkill.zhuSkill) {
							if (group in _status.zhuSkills) {
								_status.zhuSkills[group].push(skill)
							} else {
								_status.zhuSkills[group] = []
							}
						}
						if (!theSkill.zhuSkill) {
							lib.skillReplace[translate].add(skill)
						}
						_status.skillMap[skill] = name
					})
					//通过武将获取技能

					game.broadcast((translates) => {
						lib.skillReplace = translates
					}, lib.skillReplace)
					//一些同名的技能应该是支持切换的才对，把它发送给其他玩家

					game.broadcastAll((map) => {
						_status.skillMap = map
						for (const m in map) {
							lib.card[m] = {
								fullimage: true,
								image: 'character:' + map[m]
							}
						}
					}, _status.skillMap)
					//这里就是生成技能选择的那种“卡牌”就是武将原画然后旁边写着它的技能
					let num = swTool.getSelect()
					game.players.forEach(p => {
						if (!lib.playerCharacterOL[p.playerid]) {
							lib.playerCharacterOL[p.playerid] = []
						}
						const skills = skillList.randomRemove(num)
						if (!map[p.playerid]) map[p.playerid] = {}
						skills.forEach(({ skill, name }) => {
							map[p.playerid][skill] = name
							if (skill.includes("_skill")) return
							lib.playerCharacterOL[p.playerid].add(name)
						})
					})
					event.pushList = {}
					skillList.randomRemove(zhuMoreListNum).forEach(({ skill, name }) => {
						event.pushList[skill] = name
						if (skill.includes("_skill")) return
					})
					event.videoId = lib.status.videoId++;
					event.chooseTime = lib.configOL.choose_timeout

					game.broadcastAll((map, id, time, choiceNum, skillNum, listNum) => {
						lib.configOL.choose_timeout = time
						const list = Object.keys(map[game.me.playerid])
						const dialog = ui.create.dialog(`###你的技能框↓###<div class="text center">你可以选择${get.cnNumber(choiceNum) }个技能<br>如果你是地主，可以额外选择${skillNum}个技能且技能框+${listNum}</div>`, [list, 'vcardx'])
						dialog.videoId = id;
						dialog.open()
						dialog.classList.add('chooseSkills')
					}, map, event.videoId, parseInt(lib.configOL.chooseCharacter_moreTime), chooseSkillNum, zhuMoreSkillNum, zhuMoreListNum);

					event.target = game.players.randomGet();
					event.start = event.target
					event.controls = ['一倍', '两倍', '三倍', '不叫']
					game.bonusNum = 1
				}
				init()
				
				//这边就是给玩家随机分配一些技能供他们选择
				while(1) {
					event.target.classList.add("glow_phase");
					game.broadcastAll(function (id, current) {
						var dialog = get.idDialog(id);
						if (dialog) {
							if (game.me == current) dialog.content.firstChild.innerHTML = '是否叫地主？';
							else dialog.content.firstChild.innerHTML = '请等待其他玩家叫地主';
						}
					}, event.videoId, event.target);
					if (event.target != game.me && !event.target.isOnline()) await game.delay(2);

					var result = await event.target.chooseControl(event.controls).set('ai', function () {
						return _status.event.getParent().controls.randomGet();
						//return event.controls.randomGet();
					}).forResult();
					event.target.classList.remove("glow_phase");
					event.target._control = result.control;
					event.target.chat(result.control);
					if (result.control == '三倍') {
						game.bonusNum = 3;
						game.zhu = event.target;
						break;
					}
					else if (result.control != '不叫') {
						event.controls.splice(0, event.controls.indexOf(result.control) + 1);
						event.tempDizhu = event.target;
						if (result.control == '二倍') game.bonusNum = 2;
					}
					event.target = event.target.next;
					if (event.target == event.start) {
						if (event.tempDizhu) {
							game.zhu = event.tempDizhu
							break
						}
						else {
							game.broadcastAll('closeDialog', event.videoId)
							init();
						}
					}
				}

				for (var player of game.players) {
					player.identity = player == game.zhu ? 'zhu' : 'fan';
					player.showIdentity();
					player.identityShown = true
				}
				game.broadcastAll((target) => {
					target.setIdentity('zhu')
					target.identity = 'zhu'
					target.showIdentity();
					target.isZhu = true;
					target.seatNum = 1
					target.identityShown = true;
					target.addSkill(['feiyang', 'bahu'])
					game.zhu = target
				}, game.zhu)
				game.broadcastAll('closeDialog', event.videoId)
				await game.delay(1);

				const list = [];
				for (var i = 0; i < game.players.length; i++) {
					const selectButton = game.players[i] === game.zhu ? chooseSkillNum + zhuMoreSkillNum : chooseSkillNum
					const pushList = game.players[i] === game.zhu ? event.pushList : []
					const skillList = Object.keys(map[game.players[i].playerid]).addArray(Object.keys(pushList));
					list.push([game.players[i], [`你可以挑选 ${selectButton} 个作为自己的技能<br>将技能拖动到或点击到右侧的框表示选择`, [skillList, 'vcardx']], selectButton, true]);
				}
				//game.me.chooseButtonOL(list)
				const send = (current, list) => {
					var next = current.chooseItem("选择技能");
					next.set("list", [list.shift(), ["已选技能"]]);
					next.set("chooseNum", list.shift());
					next.set("forced", list.shift());
					next.set("filterMove", function (from, to, moved) {
						if (moved[0].includes(from.link)) {
							if (typeof to == "number") {
								if (to == 1) {
									if (moved[1].length >= _status.event.chooseNum) return false;
								}
								return true;
							}
						}
						return true;
					});
					next.set("filterOk", function (moved) {
						return moved[1].length == _status.event.chooseNum;
					});
					if (game.online) game.resume();
					return next;
				}
				const solve = function (resolve, reject) {
					return function (result, player) {
						if (!result || !result.moved) {
							result = "ai";
						}
						resolve({ [player.playerid]: result });
					};
				};
				var result = await Promise.allSettled(
					list.map(st => {
						const current = st.shift();
						const listSend = st;
						return new Promise(async (resolve, reject) => {
							if (current.isOnline()) {
								current.wait(solve(resolve, reject));
								current.send(send, current, listSend);
							}
							else if (current === game.me){
								if (_status.connectMode) game.me.wait(solve(resolve, reject));
								const result = await send(current, listSend).forResult();
								if (_status.connectMode) game.me.unwait(result, current);
								else solve(resolve, reject);
							}
							else {
								const result = await send(current, listSend).forResult();
								resolve({ [current.playerid]: result });
							}
						});
					})
				).catch(() => {});

				result = result
					.filter(r => r.status === 'fulfilled')
					.map(r => r.value)
					.reduce((acc, cur) => ({ ...acc, ...cur }), {});

				for (const r in result) {
					const player = lib.playerOL[r]
					let skills
					if (!result[r] || result[r] == "ai" || !result[r].moved || result[r].moved.length < 2) {
						skills = Object.keys(map[r]).randomGets(player === game.zhu ? chooseSkillNum + zhuMoreSkillNum : chooseSkillNum);
					}
					else {
						skills = result[r].moved[1].map(s => s[2])
					}
					game.addVideo('initSkill', player, { skills, me: player === game.me })
					if (player === game.me) {
						game.addVideo('closeDialog')
					}
					game.broadcastAll((player, skills) => {
						if (player === game.me) {
							let str = ''
							skills.forEach(s => str += get.translation(s) + ' ')
							player.node.rightskillList.innerHTML = str
						}
					}, player, skills)
					lib.playerSkillOL[player.playerid] = skills
				}

				//选形象
				const playerAvatarMap = {}
				game.players.forEach(p => playerAvatarMap[p.playerid] = lib.playerCharacterOL[p.playerid])

				const avatarList = [];
				game.players.forEach(player => {
					const list = playerAvatarMap[player.playerid]
					avatarList.push([player, [
						`<span style="color:red;font-weight:700;">你可以选择一个武将作为你本局的形象</span><br>
                        <span class="tempName" style="color:orange;font-weight:700;text-align:center;font-size:20px;border-radius: 5px;">还可以在下方输入框写一个名字作为本局形象名字</span><br>
                        <input maxlength="8"  style="width:45%;text-align: center;font-size: 20px;font-weight: 700;border-radius: 5px;" value="${player.nickname || get.translation(player.name1)}">`, [list, 'characterx']], 1, false])
				})//
				var result = await game.me.chooseButtonOL(avatarList, (player, result) => {
					const input = _status.event.dialog.querySelector('input')
					if (input) {
						result.tempName = input.value
					}
					if (!result.bool) return;
					if (player === game.me) {
						const character = result.links[0]
						if (character) player.node.avatar.setBackground(character, 'character')
						// player.sex = lib.character[character][0]
					}
				}).forResult()
				for (const i in result) {
					const bool = result[i]
					if (bool.tempName) {
						game.addVideo('flashName', lib.playerOL[i], {
							avatar: lib.playerOL[i].name,
							tempName: bool.tempName
						})
						game.broadcastAll((player, tempName) => {
							player.tempName = tempName
							player.node.name.innerHTML = tempName
						}, lib.playerOL[i], bool.tempName)
					}
					if (!bool.bool) continue
					game.broadcastAll((player, avatar, skills, tempName) => {
						const nickname = tempName || player.nickname || player.node.name1.innerText
						const id = nickname + player.playerid

						player.node.name.innerHTML = nickname
						player.tempName = tempName

						const characterr = swTool.copyCharacter({
							character: avatar,
							hp: 4,
							skills: skills || [],
							name: id,
							translate: nickname
						})
						characterr.trashBin.remove('hiddenSkill')
						player.init(id)
						player.update()
					}, lib.playerOL[i], bool.links[0], lib.playerSkillOL[lib.playerOL[i].playerid], bool.tempName)
					game.addVideo('flashAvatar', lib.playerOL[i], {
						avatar: bool.links[0],
						skills: lib.playerSkillOL[lib.playerOL[i].playerid]
					})
					game.addVideo('flashName', lib.playerOL[i], {
						avatar: bool.links[0],
						tempName: bool.tempName
					})
				}

				//选势力
				const select = lib.group.map(g => ['', '', `group_${g}`])
				const groupList = game.players.map(i => {
					return [i, ['你可以选择一个势力', [select, 'vcard']], 1, false]
				})
				var result = await game.me.chooseButtonOL(groupList, (player, result) => {
					if (!result.links) return
					if (player === game.me) {
						player.changeGroup(result.links[0][2].slice(6), false, false);
					}
				}).set('processAI', function () {
					return false
				}).forResult()
				for (const g in result) {
					if (!result[g].bool) continue
					const player = lib.playerOL[g]
					const group = result[g].links[0][2].slice(6)
					game.broadcastAll((player, group) => {
						lib.character[player.name1][1] = group
						player.changeGroup(group)
					}, player, group)
					game.addVideo('flashGroup', player, { group })
				}

				game.players.forEach(p => {
					const skills = lib.playerSkillOL[p.playerid]
					lib.character[p.name1].skills = skills
					_status.playerCharacters[p.playerid] = {
						player: p,
						skills: lib.character[p.name1][3],
						name: p.tempName || (p.nickname && p.nickname.replace('※', '')) || '',
						character: p.name1,
						info: lib.character[p.name1],
						group: p.group
					}
					p.addSkill(skills)
					game.broadcastAll((player, skills) => {
						lib.character[player.name1][3] = skills
						let str = ''
						skills.forEach(s => str += get.translation(s) + ' ')
						player.node.rightskillList.innerHTML = str
						if (player.nickname) {
							lib.translate[player.name1] = player.tempName || player.nickname.replace('※', '')
						}
					}, p, skills)
					game.log(`${p.node.name.innerHTML}选择了`, skills)
				})

				game.broadcastAll(() => {
					game.zhu.maxHp++
						game.zhu.hp++
						game.zhu.update()
					lib.configOL.choose_timeout = event.chooseTime
					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				})
				game.broadcastAll(swTool.setPlayersSeat(game.zhu))
				_status.playerCharactersUse = (characters, innnerHtml, needFunction) => {
					if (!window.swTool) {
						window.swTool = {
							copyCharacter: needFunction
						}
					}
					lib.skill.playerchangeSkill = {
						trigger: { player: 'changeSkillsAfter' },
						forced: true,
						charlotte: true,
						popup: false,
						filter() { return true },
						async content(event, trigger, player) {
							let str = ''
							const skills = player.getSkills(null, false, false).filter(s => get.translation(s) !== s);
							game.addVideo('initSkill', player, { skills })
							skills.forEach(i => {
								if (i === 'playerchangeSkill') return;
								const info = get.info(i);
								if (info && !info.charlotte) {
									str += get.translation(i) + ' '
								}
							});
							if (!player.node.rightskillList) {
								player.node.rightskillList = ui.create.div('.playerskillList', str, player)
							} else {
								player.node.rightskillList.innerHTML = str
							}
						}
					}
					lib.skill.PVPaozhan = {
						trigger: { global: 'dieAfter' },
						filter() { return game.players.length === 2 && !game.PVPaozhan },
						async content(event, trigger, player) {
							var color = get.groupnature(player.group, "raw");
							if (player.isUnseen()) color = "fire";
							player.$fullscreenpop("鏖战模式", color);
							game.broadcastAll(function () {
								_status._aozhan = true;
								ui.aozhan = ui.create.div(".touchinfo.left", ui.window);
								ui.aozhan.innerHTML = "鏖战模式";
								if (ui.time3) ui.time3.style.display = "none";
								ui.aozhanInfo = ui.create.system("鏖战模式", null, true);
								lib.setPopped(
									ui.aozhanInfo,
									function () {
										var uiintro = ui.create.dialog("hidden");
										uiintro.add("鏖战模式");
										var list = [
											"当游戏中仅剩两名玩家",
											"在鏖战模式下，任何角色均不是非转化的【桃】的合法目标。【桃】可以被当做【杀】或【闪】使用或打出。",
											"进入鏖战模式后，即使之后有两名或者更多的角色出现，仍然不会取消鏖战模式。",
										];
										var intro = '<ul style="text-align:left;margin-top:0;width:450px">';
										for (var i = 0; i < list.length; i++) {
											intro += "<li>" + list[i];
										}
										intro += "</ul>";
										uiintro.add('<div class="text center">' + intro + "</div>");
										var ul = uiintro.querySelector("ul");
										if (ul) {
											ul.style.width = "180px";
										}
										uiintro.add(ui.create.div(".placeholder"));
										return uiintro;
									},
									250
								);
								game.playBackgroundMusic();
							});
							game.countPlayer(function (current) {
								current.addSkill("aozhan");
							});
						},
						forced: true,
						charlotte: true,
					}
					const style = document.createElement('style')
					style.innerHTML = innnerHtml
					document.head.appendChild(style)
					for (const s in characters) {
						const { skills, name, character, info, group } = characters[s]
						skills.push('playerchangeSkill')
						lib.character[character] = info
						const thecharacter = lib.character[character]
						if (!thecharacter) continue
						thecharacter.group = group
						thecharacter.trashBin.remove('hiddenSkill')
						thecharacter.skills = skills
						lib.translate[character] = name || get.translation(character)
					}
					const oldme = ui.create.me
					ui.create.me = () => {
						const me = oldme.call(this, ...arguments)
						for (const s in characters) {
							const player = lib.playerOL[s]
							// const {skills,name} = characters[s]
							const { skills } = characters[s]
							let str = ''
							skills.forEach(s => {
								if (s === 'playerchangeSkill') return;
								str += get.translation(s) + ' '
							})
							if (!player.node.rightskillList) player.node.rightskillList = ui.create.div('.playerskillList', player)
							player.node.rightskillList.innerHTML = str
							// if(name) player.node.name.innerHTML = name
							const { x } = player.getBoundingClientRect()
							if (ui.window.clientWidth - x < 200) {
								player.classList.add('rightPlayer')
							} else if (x > 0 && x < 400) {
								player.classList.add('leftPlayer')
							}
						}
						ui.create.me = oldme
						return me
					}
				}
				game.broadcastAll(() => {
					lib.skill.playerchangeSkill = {
						trigger: { player: 'changeSkillsAfter' },
						forced: true,
						charlotte: true,
						popup: false,
						filter() { return true },
						async content(event, trigger, player) {
							let str = ''
							const skills = player.getSkills(null, false, false).filter(s => get.translation(s) !== s);;
							skills.forEach(i => {
								if (i === 'playerchangeSkill') return;
								const info = get.info(i);
								if (info && !info.charlotte) {
									str += get.translation(i) + ' '
								}
							});
							if (!player.node.rightskillList) {
								player.node.rightskillList = ui.create.div('.playerskillList', player)
							}
							game.broadcastAll((player, str) => {
								player.node.rightskillList.innerHTML = str
							}, player, str)
						}
					}
				})
				game.addGlobalSkill('playerchangeSkill')
			})
		}
	}
}
